# save_listener.py
# -------------
# Author: Zako888y
#
# This file is dedicated to the public domain under the Creative Commons CC0 1.0 Universal (CC0 1.0) Public Domain Dedication.
# You may use, copy, modify, distribute, and/or sell this code for any purpose, without restriction. No warranty is provided. The author waives all rights and claims to this work worldwide.
# To view a copy of this dedication, visit https://creativecommons.org/publicdomain/zero/1.0/

import os
import soundfile as sf

import sys

sys.path.append(os.path.dirname(__file__))

from segmenter import SegmentListener


class SaveListener(SegmentListener):

    def __init__(self, save_dir="./save"):
        self.save_dir = save_dir
        os.makedirs(self.save_dir, exist_ok=True)
        self.counter = 0

    def on_segment(self, audio_data, samplerate):
        # 自动递增文件名
        filename = os.path.join(self.save_dir, f"sentence_{self.counter:04d}.wav")
        sf.write(filename, audio_data, samplerate)
        print(f"已保存: {filename}")
        self.counter += 1


# 用法示例：
if __name__ == "__main__":
    from segmenter import SpeechSegmenter

    listener = SaveListener()
    tts = SpeechSegmenter(listener=listener)
    tts.start()
    input()
